package com.example.demo.filter;

import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request; //强转成HttpServletRequest对象     req
//        1. 获取请求url
        String uri = req.getRequestURI();
        log.info("uri:{}",uri);
//        2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(uri.contains("login")){
            chain.doFilter(request,response);
            return;
        }
        HttpServletResponse resp = (HttpServletResponse) response;
//        3. 获取请求头中的令牌（token）
        String token = req.getHeader("token");
//        4. 判断令牌是否存在，如果不存在，响应 401
        if (token == null){
            resp.setStatus(401);
            log.info("令牌为空");
            return;
        }
//        5. 解析token，如果解析失败，响应 401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("claims = {}",claims);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败");
            resp.setStatus(401);
            return;
        }
//        6. 放行
        log.info("令牌合法, 放行");
        chain.doFilter(request,response);
    }
}
